#!/usr/bin/env python
# encoding=utf-8

from flask import *
from wechatpy import parse_message

from . import wechat
from .service import handle_msg
from .. import dao


@wechat.route('/wechat', methods=['GET', 'POST'])
def wechat_():
    if request.method == u'GET':
        return request.args.get(u'echostr')
    msg = parse_message(request.data)

    reply = handle_msg(msg)

    return reply.render()


@wechat.route('/wechat/detail/<sid>')
def detail(sid):
    data = dao.render_anno_db(dao.select_db_single('stockAnnouncement', {'_id': sid}))
    # file_meta = dao.select_db_single('fileMetaData', {'key': data['file']}, db='qiniu')
    # if not file_meta:
    #     file_meta = {}
    # filesize = float(file_meta.get('filesize', 0))
    # if filesize <= (1 << 20):
    #     filesize = '%dKB' % int((filesize + 512) / 1024)
    # else:
    #     filesize = '%.2fMB' % (filesize / 1024 / 1024)
    # data['filesize'] = filesize
    # param = {
    #     'data': data,
    #     'title': u'(%s-%s) %s' % (data['companyShortName'], data['stockCode'], data['title']),
    # }
    # return render_template('wechat/detail.html', **param)
    return redirect('http://file001.socialcredits.cn/' + data['file'])


@wechat.route('/wechat/search/<key>')
@wechat.route('/wechat/search/<key>/<int:page>')
def search(key, page=1):
    if page > 10:
        return redirect(u'/wechat/search/' + key)

    total, data = dao.select_es(key, page)
    param = {
        'title': key,
        'keyword': key,
        'data': data,
        'total': total,
        'pages': calc_page_bar(page, max_page=(total + 9) / 10),
    }
    # flash(u'您目前搜索条件为：%s，共搜索到%s条记录。' % (key, total))
    return render_template('wechat/search.html', **param)


def calc_page_bar(page, max_page=None):
    if page == 1:
        pages = [1, 2, 1, 1, 2, 3, 4, 5]
    elif page == 2:
        pages = [1, 3, 2, 1, 2, 3, 4, 5]
    else:
        pages = [page - 1, page + 1, page] + range(page - 2, page + 3)
    if isinstance(max_page, int):
        if max_page < pages[1]:
            pages[1] = max_page
        pages = pages[:3] + [x for x in pages[3:] if x <= max_page]
    return pages
